<script setup lang="ts">
import { onMounted, ref } from "vue";
import * as PIXI from "pixi.js";
import { Live2DModel } from "pixi-live2d-display";
import { MotionSync } from "live2d-motionsync";
// import { Button, Card, Input, Select, Space, Spin } from "antd";
import { modelMap } from "../config/models";
// import { tts, ttsTwo } from "../config/tts.ts";

const tts = async (text: string) => {
  const response = await fetch("https://edge-tts-stream-api.vercel.app/tts/stream", {
    method: "POST",
    body: JSON.stringify({
      voice: "zh-CN-XiaoxiaoNeural",
      text,
    }),
    headers: {
      "Content-Type": "application/json",
    },
  }).then((res) => res.arrayBuffer());
  return response;
};

(window as any).PIXI = PIXI;

async function arrayBufferToAudioBuffer(arrayBuffer: ArrayBuffer) {
  // 创建 AudioContext 实例
  const audioContext = new AudioContext();

  // 使用 decodeAudioData 解码 ArrayBuffer
  const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);

  return audioBuffer;
}

const canvasRef = ref<HTMLCanvasElement>(null);

// const play = async () => {
//   debugger;
//   if (!motionSync.current) return;
//   const buffer = await tts(text);
//   const audioBuffer = await arrayBufferToAudioBuffer(buffer);
//   motionSync.current.play(audioBuffer);
// };

let app: any;
let model;
let motionSync = {
  current: null,
};

const loadModel = async () => {
  if (!canvasRef.value) return;
  const modelUrl =
    "http://localhost:5173/live2d-motionSync/models/kei_vowels_pro/kei_vowels_pro.model3.json";
  app = new PIXI.Application({
    view: canvasRef.value,
    resizeTo: canvasRef.value.parentElement || undefined,
    backgroundAlpha: 0,
  });
  model = await Live2DModel.from(modelUrl, { autoInteract: false });

  // 获取模型横纵比
  const modelRatio = model.width / model.height;
  const centerModel = () => {
    // 让模型height为画布一半
    model.height = app.view.height;
    model.width = model.height * modelRatio;
    model.x = (app.view.width - model.width) / 2;
    model.y = 0;
  };

  centerModel();
  app.stage.addChild((model as unknown) as PIXI.DisplayObject);

  motionSync.current = new MotionSync(model.internalModel);
  motionSync.current.loadMotionSyncFromUrl(
    modelUrl.replace(/.model(.)?.json/, ".motionsync3.json")
  );
  //   setLoading(false);
};

onMounted(() => {
  loadModel();
  //   setTimeout(() => {
  //     motionSync.current.play("./sayhi.wav");
  //   }, 1000);
});

const play = () => {
  motionSync.current.play("./sayhi.wav");
};
</script>

<template>
  <div>
    <div @click="play">播放</div>
    <canvas ref="canvasRef" width="800" height="600"></canvas>
  </div>
</template>
